<template>
  <div class="page-mobile-test__record">
    <van-tabs v-model="active" sticky>
      <van-tab name="test-center" title="考试中心">
        <div class="no-data" v-if="paper_list.length == 0">
          <van-empty description="暂时没有试卷哦~" />
        </div>
        <div class="test-center" v-if="paper_list.length > 0">
          <div class="card-test-box">
            <exam-card
              v-for="(item, index) in paper_list"
              :key="index"
              :course_record_list="course_record_list"
              :detail="item"
            ></exam-card>
          </div>
        </div>
      </van-tab>
      <van-tab name="wrong-note" title="考试记录">
        <div class="no-data" v-if="record_list.length == 0">
          <van-empty description="暂无考试记录~" />
        </div>
        <div
          class="record_card"
          v-for="(item, index) in record_list"
          :key="index"
          v-if="record_list.length > 0"
          @click="toPath('/m/test-log?paper_id='+item.paperId+'&test_log_id='+item.id)"
        >
          <div class="record_left">
            <van-icon name="notes-o" />
          </div>
          <div class="record_right">
            <div class="record_title">{{ item.paperName }}</div>
            <div class="record_detail">
              <span
                :class="['record_result', is_pass(item) ? 'success' : 'error']"
                >{{ is_pass(item) ? "合格" : "不及格" }}</span
              >
              <span class="record_time">{{ trimDate(item.createTime) }}</span>
            </div>
          </div>
          <div :class="['record_score', is_pass(item) ? 'success' : 'error']">
            <span :class="['score_num']">{{ item.score }}</span
            >分
          </div>
        </div>
      </van-tab>
    </van-tabs>
    <!-- <van-empty description="暂无考试记录" v-if="record_list.length == 0" />
    <van-empty
      :description="$t('locale.mobile.testRecord.t1')"
      v-if="record_list.length == 0"
    />
    <div
      class="record_card"
      v-for="(item, index) in record_list"
      :key="index"
      v-if="record_list.length > 0"
    >
      <div class="record_left">
        <van-icon name="notes-o" />
      </div>
      <div class="record_right">
        <div class="record_title">{{ item.paperName }}</div>
        <div class="record_detail">
          <span :class="['record_result']" v-if="item.status == 1">{{
            "等待评分中"
          }}</span>
          <span
            v-if="item.status == 2"
            :class="['record_result', is_pass(item) ? 'success' : 'error']"
            >{{
              is_pass(item)
                ? $t("locale.mobile.testRecord.t2")
                : $t("locale.mobile.testRecord.t3")
            }}</span
          >
          <span class="record_time">{{ trimDate(item.createTime) }}</span>
        </div>
      </div>
      <div
        :class="['record_score', is_pass(item) ? 'success' : 'error']"
        v-if="item.status == 2"
      >
        <span :class="['score_num']">{{ item.score }}</span
        >分
      </div>
    </div> -->
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import { paperTestList,getPaperMine } from "~/api/test";
import { getOrderList } from "~/api/order";
import ExamCard from "~/components/mobile/ExamCard.vue";
export default {
  scrollToTop: true,
  components: {
    ExamCard
  },
  // head() {
  //   return {
  //     meta: [
  //       {
  //         "http-equiv": "Content-Security-Policy",
  //         content: "upgrade-insecure-requests"
  //       }
  //     ]
  //   };
  // },
  props: ["setDisabled", "refreshFun", "setLoading"],
  data() {
    return {
      page: 1,
      pageSize: 10,
      total: 0,
      record_list: [],
      active: "my-test",
      left: 0,
      paper_list: [] //试卷列表
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      major_list(state) {
        return state.major_list;
      },
      token(state) {
        return state.token;
      },
      is_loading(state) {
        return state.is_loading;
      }
    })
  },
  watch: {},
  activated() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
        return;
      }
      window.addEventListener("scroll", this.eventListener);
    }
    this.getData();


    this.setDisabled(false);
    this.refreshFun(() => {
      this.getData();
      this.getCoursesMine();
      this.setLoading(false);
    });
  },
  deactivated() {
    this.setDisabled(true);
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
    this.initState();
  },
  destroyed() {
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
    this.initState();
  },
  methods: {
    ...mapMutations(["SET_IS_LOADING", "SET_COURSE_RECORD_LIST"]),
    toPath(path) {
      // console.log(path);
      this.$router.push(path);
    },
    async getTestPapers(buy_record_list) {
      this.SET_IS_LOADING(false);
      let params = {
        courseId: JSON.stringify(buy_record_list.map(i => i.courseId))
      };
      let result = await getPaperMine(params);
      if (result && result.data && result.data.code == 200) {
        this.paper_list = result.data.data;
        this.SET_IS_LOADING(false);
      } else {
        this.$toast("获取失败！");
        this.SET_IS_LOADING(false);
      }
    },
    async getCoursesMine() {
      this.SET_IS_LOADING(true);
      let params = {
        userId: this.user_info.id
      };
      let result = await getOrderList(params);
      if (result && result.data && result.data.code == 200) {
        this.course_record_list = result.data.data;
        this.SET_COURSE_RECORD_LIST(result.data.data);

        this.getTestPapers(
          result.data.data.map(i => {
            return {
              ...i,
              courseId: i.courseId
            };
          })
        );
      } else {
        this.$toast("获取失败！");
        this.SET_IS_LOADING(true);
      }
    },
    async getData(fetch_type) {
      this.SET_IS_LOADING(true);
      let result = await paperTestList({
        userId: this.user_info.id,
        sort: "id desc",
        offset: this.pageSize * (this.page - 1),
        limit: this.pageSize
      });
      if (result && result.data && result.data.code == 200) {
        const { data } = result.data;
        if (fetch_type == "pullup") {
          this.record_list = [...this.record_list, ...data.rows];
        } else {
          this.record_list = data.rows;
        }
        this.total = data.total;
      } else {
        this.$toast(
          this.$t("locale.mobile.testRecord.t4") + result &&
            result.data &&
            result.data.msg
        );
        this.SET_IS_LOADING(false);
      }
      this.SET_IS_LOADING(false);
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function() {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      if (scrollTop + clientHeight >= scrollHeight) {
        console.log("上拉加载");
        if (this.total <= this.record_list.length) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        this.page++;
        this.getData("pullup");
      }
    },
    eventListener() {
      this.throttle(this.pullUp, 30);
    },
    getMajorName(item) {
      let res = this.major_list.filter(i => i.id == item.majorId);
      if (res.length > 0) {
        return res[0].name;
      } else {
        return this.$t("locale.mobile.testRecord.unknow");
      }
    },
    trimDate(date) {
      if (date) {
        let _date = new Date(date);
        return `${_date.getFullYear()}.${_date.getMonth() +
          1}.${_date.getDate()}  ${_date.getHours()}:${_date.getMinutes()}`;
      } else {
        return this.$t("locale.mobile.testRecord.unknow");
      }
    },
    is_pass(item) {
      if (!item.score) {
        return false;
      } else {
        if (item.score < item.passScore) {
          return false;
        } else {
          return true;
        }
      }
    },
    initState() {
      this.page = 1;
      this.pageSize = 10;
      this.total = 0;
      this.record_list = [];
    }
  },
  created() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
      }
    }
    this.setDisabled(false);
    this.getData();
    this.getCoursesMine();
    this.refreshFun(() => {
      this.getData();
      this.getCoursesMine();
      this.setLoading(false);
    });
    // this.getData();
    // this.getCoursesMine();
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  }
};
</script>

<style lang="scss" scoped>
.page-mobile-test__record {
}
</style>
<style lang="scss">
.page-mobile-test__record {
  min-height: calc(100vh - 1.6rem);
  background-color: #f9f8f8;
  padding: 0 0 0.2rem 0;
  .van-sticky--fixed {
    top: 0.8rem;
  }
  .test-center {
    padding: 0.2rem 0;
  }
  .success {
    border-color: #49cc90 !important;
    color: #49cc90 !important;
  }
  .error {
    border-color: #f93e3e !important;
    color: #f93e3e !important;
  }
  .record_card {
    display: flex;
    padding: 0.1rem 0.2rem;
    .record_left {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 1.2rem;
      height: 1.2rem;
      border-radius: 1.2rem;
      background-color: var(--theme-color);
      .van-icon {
        font-size: 0.6rem;
        color: #fff;
      }
    }
    .record_right {
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding-left: 0.2rem;
      flex: 1;
      .record_title {
        font-size: 0.26rem;
        text-align: left;
        font-family: PingFangSC-regular;
      }
      .record_detail {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        margin-top: 0.2rem;
        .record_result {
          &::after {
            content: "";
            display: inline-block;
            margin: 0 0.1rem 0 0.1rem;
            width: 0.04rem;
            height: 0.2rem;
            background-color: #bbbbbb;
            vertical-align: text-bottom;
          }
        }
        .record_time {
          color: #7b7979;
          font-size: 0.24px;
          text-align: left;
          font-family: PingFangSC-regular;
        }
      }
    }
    .record_score {
      width: 1rem;
      height: 1rem;
      line-height: 1rem;
      text-align: center;
      font-size: 0.28rem;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      border: 0.04rem solid var(--theme-color);
      // border: none;
      border-radius: 50%;
      transition: all 0.3s ease;
      .score_num {
        margin-right: 0.02rem;
      }
    }
  }
}
</style>
